package client

import (
	"context"
	"fmt"
	"gitee.com/enjoy_5/goods-rpc/proto/goods"
	"gitee.com/xuxinzhi2206/corehub/nacos"
	"google.golang.org/grpc"
)

const SERVICE = "goods-srv"

const GroupName = "DEFAULT_GROUP"

func client(hand func(c goods.GoodsClient) error) error {
	// 1.连接
	service, err := nacos.FindService(SERVICE, GroupName)
	if err != nil {
		return fmt.Errorf("find server err:%v", err)
	}
	conn, err := grpc.Dial(service, grpc.WithInsecure())
	if err != nil {
		return fmt.Errorf("连接异常:%v", err)
	}
	defer conn.Close()
	c := goods.NewGoodsClient(conn)
	return hand(c)
}

// ..
func GetGoodsInfo(ctx context.Context, id int64) (info *goods.GoodsInfo, err error) {
	err = client(func(c goods.GoodsClient) error {
		goodInfo, err := c.GetGoodInfo(ctx, &goods.GetGoodInfoRequest{
			ID: id,
		})
		if err != nil {
			return err
		}
		info = goodInfo.GetInfo()
		return nil
	})
	return
}

func GetSkuInfoByPropertyValueIDs(ctx context.Context, PropertyValueId1, PropertyValueId2, PropertyValueId3 int64) (info *goods.SkuInfo, err error) {
	err = client(func(c goods.GoodsClient) error {
		res, err := c.GetSkuInfoByPropertyValueIDs(ctx, &goods.GetSkuInfoByPropertyValueIDsRequest{
			PropertyValueId1: PropertyValueId1,
			PropertyValueId2: PropertyValueId2,
			PropertyValueId3: PropertyValueId3,
		})
		if err != nil {
			return err
		}
		info = res.GetInfo()
		return nil
	})
	return
}
func SearchGoodsByTitle(ctx context.Context, title string, page, pageSize int64) (info []*goods.GoodsInfo, err error) {
	err = client(func(c goods.GoodsClient) error {
		res, err := c.SearchGoodsByTitle(ctx, &goods.SearchGoodsByTitleRequest{
			Title:    title,
			Page:     page,
			PageSize: pageSize,
		})
		if err != nil {
			return err
		}
		info = res.GetInfo()
		return nil
	})
	return
}

// 根据skuID获取信息
func GetSkuInfoByIDs(ctx context.Context, SkuID int64) (info *goods.SkuInfo, err error) {
	err = client(func(c goods.GoodsClient) error {
		res, err := c.GetSkuInfoByID(ctx, &goods.GetSkuInfoByIDRequest{SkuID: SkuID})
		if err != nil {
			return err
		}
		info = res.GetInfo()
		return nil
	})
	return
}

// 根据切片skuID获取信息
func GetGoodsInfoBySkuIds(ctx context.Context, SkuID []int64) (list *goods.GetGoodsListBySkuIDResp, err error) {
	return list, client(func(c goods.GoodsClient) error {
		list, err = c.GetGoodsList(ctx, &goods.GetGoodsListBySkuIDReq{SkuID: SkuID})
		if err != nil {
			return err
		}
		return nil
	})
}

// 商品列表
func GoodsList(ctx context.Context, page, pageSize, typeID int64, title string) (info []*goods.GoodListInfo, err error) {
	err = client(func(c goods.GoodsClient) error {
		res, err := c.GoodList(ctx, &goods.GoodListRequest{
			Page:     page,
			PageSize: pageSize,
			TypeID:   typeID,
			Title:    title,
		})
		if err != nil {
			return err
		}
		info = res.GetIn()
		return nil
	})
	return
}
